﻿// 
//    Copyright 2010 The JaernCloud Project
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using JaernCloud.Web.Scopes;
using JaernCloud.Language.Compiler.Types;
using JaernCloud.Language.Runtime;
using JaernCloud.Language.Compiler;
using JaernCloud.Language.Compiler.Ast;
using JaernCloud.Language.Runtime.View;
using JaernCloud.Web.Configuration;
using System.IO;
using JaernCloud.Web.Ajax;
using JaernCloud.Language.Compiler.Types.Builtin.View;

namespace JaernCloud.Web.Controllers {
    
    /// <summary>
    /// Base class for JaernCloud enabled controllers
    /// </summary>
    public abstract class JaernCloudController : Controller {

        private NodeObjectScopeProvider _scopes;
        private NodeObjectGenerator _generator;
        private JaernCloudConfiguration _configuration;
        private JaernCloudServerContext _serverContext;

        public RootNodeType GetRootNodeType(string fileName) {
            
            // TODO: Use custom view engine or cache file buffer
            Parser parser = new Parser(new Scanner(fileName));
            parser.Parse();
            
            RootNodeType root = new RootNodeType(parser.Root, true);

            foreach (AstNode node in parser.Root.Children) {
                INodeType type = NodeTypeGenerator.GetNodeTypeInstanceFor(node);
                root.AddChild(type);
            }

            return root;
        }

        public string Render(ViewNodeObject view) {
            StringWriter writer = new StringWriter();
            view.Render(view, writer);
            return writer.ToString();
        }

        public JaernCloudConfiguration Configuration {
            get {
                if (_configuration == null) {
                    _configuration = new JaernCloudConfiguration();
                }
                return _configuration;
            }
        }

        public JaernCloudServerContext ServerContext {
            get {
                if(_serverContext == null) {
                    _serverContext = new JaernCloudServerContext();
                }
                return _serverContext;
            }
            set {
                _serverContext = value;
            }
        }

        public string ControllerName {
            get {
                return this.GetType().Name.Replace("Controller", string.Empty);
            }
        }

        /// <summary>
        /// Returns the default view
        /// </summary>
        public ViewNodeObject GetView() {
            return GetView(null);
        }

        public IViewNodeType GetViewType() {
            return GetViewType(null);
        }

        private string GetViewFileName(string name) {
            if (name == null) {
                name = ControllerName + "/" + ControllerName + ".jcl";
            }
            var fileName = ServerContext.MapPath(this, "~/Views/" + name);
            return fileName;
        }

        /// <summary>
        /// Returns the specified view
        /// </summary>
        public ViewNodeObject GetView(string name) {


            var fileName = GetViewFileName(name);

            RootNodeType root = GetRootNodeType(fileName);
            foreach (INodeType type in root.Children) {
                if (type is IViewNodeType) {
                    
                    ViewNodeObject viewNode = (ViewNodeObject)Generator.GetNodeObjectInstanceFor(type);                    
                    viewNode.Expand(false);

                    // test basic DLR integration
                    var testDLR = false;
                    if (testDLR) {
                        dynamic view = viewNode;
                        int currentTickCount = view.counter.count;
                        view.counter.count = Environment.TickCount;
                    }

                    return viewNode;
                }
            }

            return null;

            // TOOD Create custom view engine
            // will try "Index" first, then name of controller
            // ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, name, null);
            //if (viewResult.View == null) {
            //   throw new HttpException(404, "404 - View Not Found");
            //}

        }

        public IViewNodeType GetViewType(string name) {
            var fileName = GetViewFileName(name);
            RootNodeType root = GetRootNodeType(fileName);
            foreach (INodeType type in root.Children) {
                if (type is IViewNodeType) {
                    return type as IViewNodeType;
                }
            }
            return null;
        }

        #region Ajax

        /// <summary>
        /// Perform an ajax action using a jquery JSON request
        /// </summary>
        [HttpPost]
        public virtual ActionResult DoAjax([ModelBinder(typeof(JSONModelBinder))] JSONString request) {
            var viewType = GetViewType();
            var ajaxAction = new JaernCloudAjaxAction(this);
            return ajaxAction.ProcessAjaxAction(viewType, request);
        }

        #endregion

        public NodeObjectScopeProvider Scopes {
            get {
                if (_scopes == null) {
                    _scopes = new NodeObjectScopeProvider(this);
                }
                return _scopes;
            }
            set {
                _scopes = value;
            }
        }

        public NodeObjectGenerator Generator {
            get {
                if (_generator == null) {
                    _generator = new NodeObjectGenerator(Scopes);
                }
                return _generator;
            }

        }

    }
}
